package com.gin.kotlin.gf2gamecommunity.app

import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.gin.kotlin.enums.CommentSort
import com.gin.kotlin.gf2gamecommunity.base.enums.ImageShow
import com.gin.kotlin.gf2gamecommunity.base.util.StoreValue


private val Context.settings by preferencesDataStore("settings")

/**
 * 打开主题时默认的回复排序方式
 * @param content (value: CommentSort, update: (CommentSort) -> Unit) -> Unit
 */
@Composable
fun DefaultCommentSort(content: @Composable (value: CommentSort, update: (CommentSort) -> Unit) -> Unit) =
    StoreValue(datastore = LocalContext.current.settings,
        preferencesKey = intPreferencesKey("default_comment_sort"),
        defaultValue = CommentSort.NORMAL,
        encode = { it.ordinal },
        decode = { o -> CommentSort.entries.firstOrNull { it.ordinal == o } ?: CommentSort.NORMAL },
        content)

/**
 * 图片显示策略配置
 * @param key key
 * @param defaultValue ImageShow
 * @param content (value: ImageShow, update: (ImageShow) -> Unit) -> Unit
 */
@Composable
fun ImageShowSetting(
    key: String,
    defaultValue: ImageShow = ImageShow.WIFI,
    content: @Composable (value: ImageShow, update: (ImageShow) -> Unit) -> Unit
) = StoreValue(datastore = LocalContext.current.settings,
    preferencesKey = intPreferencesKey(key),
    defaultValue = defaultValue,
    encode = { it.ordinal },
    decode = { o -> ImageShow.entries.firstOrNull { it.ordinal == o } ?: defaultValue },
    content)

/**
 * 主题列表中的镇楼图显示策略
 * @param content (value: ImageShow, update: (ImageShow) -> Unit) -> Unit
 */
@Composable
fun TopicImageShow(content: @Composable (value: ImageShow, update: (ImageShow) -> Unit) -> Unit) = ImageShowSetting("topic_image_show", content = content)

/**
 * 回复正文中的图片显示策略
 * @param content (value: ImageShow, update: (ImageShow) -> Unit) -> Unit
 */
@Composable
fun CommentImageShow(content: @Composable (value: ImageShow, update: (ImageShow) -> Unit) -> Unit) = ImageShowSetting("comment_image_show", content = content)

/**
 * 头像显示策略
 * @param content (value: ImageShow, update: (ImageShow) -> Unit) -> Unit
 */
@Composable
fun AvatarImageShow(content: @Composable (value: ImageShow, update: (ImageShow) -> Unit) -> Unit) = ImageShowSetting("avatar_image_show", content = content)
